package ch.unisi.inf.pfii.teamred.pacman.model;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * This class describes a pacman in the Pacman game.
 * 
 * @author luca.vignola@lu.unisi.ch
 * @author mark.pruneri@lu.unisi.ch
 * 
 */

public final class Pacman extends PlayerControlledCreature {

	public Pacman(final Position startPosition, final Direction currentDirection) {
		super(startPosition, currentDirection);
		setVulnerable();
		setName("pacman");
	}

	protected final int handleCurrentCreatures() {
		int totalPointsToAdd = 0;

		if (!isVulnerable()) {
			for (Creature creature : getCreaturesOnCurrentFloor()) {
				if (creature != this) {
					totalPointsToAdd += creature.getPoints();
				}
			}
		}
		return totalPointsToAdd;
	}

	protected final int handleCurrentItems() {
		int totalPointsToAdd = 0;
		ArrayList<Item> itemsOnCurrentFloor = getCurrentItems();
		Iterator<Item> it = itemsOnCurrentFloor.iterator();

		while (it.hasNext()) {
			Item item = it.next();
			totalPointsToAdd += handleItem(item);
			it.remove();
		}

		return totalPointsToAdd;
	}

	public final void reset() {
		setVulnerable();
		setCurrentPosition(getStartPosition());
		resetTimer();
	}

	private final void setToDead() {
		setDead();
		setVulnerable();
		resetTimer();
	}

	private final int handleItem(final Item item) {
		if (item != null) {
			return item.doAction(this);
		} else {
			return 0;
		}
	}

	private final void eatCurrentCreatures() {
		for (final Creature creature : getCreaturesOnCurrentFloor()) {
			if (creature != this) {
				creature.setDead();
			}
		}
	}

	public final void updateStatus() {
		if (!currentAiControlledCreaturesAreVulnerable()) {
			setToDead();
		} else {
			eatCurrentCreatures();
			decrementTimer();
		}
	}

	public final String toString() {
		return "P";
	}
}
